<template>
  <PageWrapper title="软件价格">
    <div id="price">
      <a-card>
        <a-table
          :columns="columns"
          :data-source="dataSource"
          bordered
          :row-selection="rowSelection"
          :pagination="false"
          rowKey="softwareId"
        >
          <template #bodyCell="{ column, text, record }">
            <template v-if="column.dataIndex === 'operation'">
              <div class="editable-row-operations">
                <span v-if="editableData[record.softwareId]">
                  <a-typography-link @click="save(record.softwareId)">保存</a-typography-link>
                  <a-popconfirm title="确定保存？" @confirm="cancel(record.softwareId)">
                    <a>取消</a>
                  </a-popconfirm>
                </span>
                <span v-else>
                  <a @click="edit(record.softwareId)">编辑</a>
                </span>
              </div>
            </template>
            <template v-else>
              <div>
                <template v-if="editableData[record.softwareId]">
                  <a-input
                    v-if="column.dataIndex != 'payDate'"
                    v-model:value="editableData[record.softwareId][column.dataIndex]"
                    style="margin: -5px 0"
                  />
                  <a-date-picker
                    format="YYYY-MM-DD"
                    valueFormat="YYYY-MM-DD"
                    v-else
                    v-model:value="editableData[record.softwareId][column.dataIndex]"
                  />
                </template>
                <template v-else>
                  {{ text }}
                </template>
              </div>
            </template>
          </template>
        </a-table>
        <a-space class="btn-group"> </a-space>
        <a-row justify="space-between" class="mt-4">
          <a-col>
            <a-pagination v-model:current="pageNo" :total="totalPage" @change="changePage" />
          </a-col>

          <a-col>
            <a-space class="btn-group">
              <!-- <a-button @click="onSubmit" v-if="userId">提交</a-button>  -->
              <a-button type="primary" @click="onSend">发送</a-button>
            </a-space></a-col
          ></a-row
        >
      </a-card></div
    >
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { PageWrapper } from '/@/components/Page'
  import { cloneDeep } from 'lodash-es'
  import type { TableProps } from 'ant-design-vue'
  import { message, Modal } from 'ant-design-vue'
  import { reactive, ref, onMounted, useId } from 'vue'
  import type { UnwrapRef } from 'vue'
  import { getList, addPrice, commitPay, send } from '/@/api/sys/product'
  import { useRoute } from 'vue-router'
import { router } from '/@/router'
  //当前页码
  const pageNo = ref(1)
  // 总页码
  const totalPage = ref(0)
  const token = localStorage.getItem('TOKEN_KEY')
  const route = useRoute()
  const userId = ref(route.query.userId || undefined)
  //选中数据
  interface DataType {
    userId: string
    softwareId: string
    partnerRentRowId: string
  }
  const selectedRowKeys = ref<string[]>([])
  const selectedRows = ref<DataType[]>([])
  const rowSelection: TableProps['rowSelection'] = {
    columnTitle: '选择',
    type: 'radio',
    columnWidth: 80,
    fixed: true,
    preserveSelectedRowKeys: true,
    onChange: (keys: string[], rows: DataType[]) => {
      selectedRowKeys.value = keys
      selectedRows.value = rows
    },
  }

  const columns = ref([
    {
      title: '软件名字',
      dataIndex: 'softwareName',
      key: 'softwareName',
    },
    {
      title: '短租',
      children: [
        {
          title: '租金',
          dataIndex: 'shortRent',
          key: 'shortRent',
          width: 100,
        },
        {
          title: '天数',
          dataIndex: 'shortDay',
          key: 'shortDay',
          width: 100,
        },
      ],
    },
    {
      title: '长租',
      children: [
        {
          title: '租金',
          dataIndex: 'longRent',
          key: 'longRent',
          width: 100,
        },
        {
          title: '天数',
          dataIndex: 'longDay',
          key: 'longDay',
          width: 100,
        },
      ],
    },
    {
      title: '购买价格',
      dataIndex: 'price',
      key: 'price',
    },
  ])
  const columns2 = ref([
    {
      title: '到账日期',
      dataIndex: 'payDate',
      key: 'payDate',
    },
    {
      title: '到账金额',
      dataIndex: 'payAmount',
      key: 'payAmount',
    },
  ])
  const columns3 = ref([
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      fixed: 'right',
      width: 110,
    },
  ])
  const dataSource = ref([])
  async function getTable() {
    const params = {
      token,
      userId: userId.value || '',
      // pageNo: pageNo.value,
    }
    const res = await getList(params)
    totalPage.value = res.data.totalPage
    dataSource.value = res.data
  }
  function changePage() {
    getTable()
  }
  // 页面加载时自动执行
  onMounted(() => {
    if (userId.value) {
      columns.value.splice(5, 0, ...columns2.value)
    }
    columns.value.push(...columns3.value)

    getTable()
  })
  interface DataItem {
    softwareId: string
    softwareName: string
    shortRent: number
    shortDay: number
    longRent: number
    longDay: number
    price: number
    payDate: string
    payAmount: number
  }

  const editableData: UnwrapRef<Record<string, DataItem>> = reactive({})

  const edit = (key: string) => {
    editableData[key] = cloneDeep(
      dataSource.value.filter((item: DataItem) => key === item.softwareId)[0],
    )
    // console.log(editableData[key])
  }
  // 保存
  const save = async (key: string) => {
    const res = await addPrice({
      token,
      data: {
        softwareId: editableData[key].softwareId,
        softwareName: editableData[key].softwareName,
        shortRent: editableData[key].shortRent,
        shortDay: editableData[key].shortDay,
        longRent: editableData[key].longRent,
        longDay: editableData[key].longDay,
        price: editableData[key].price,
      },
    })
    if (userId.value) {
      const data = await commitPay({
        token,
        data: {
          softwareId: editableData[key].softwareId,
          userId: userId.value,
          payDate: editableData[key].payDate,
          payAmount: editableData[key].payAmount,
        },
      })
      
      if (res.success && data.success === 1) {
        message.success('成功')
      } else {
        message.error(data.message)
      }
    } else {
      if (res.success === 1) {
        message.success('成功')
      } else {
        message.error(res.message)
      }
    }

    dataSource.value = []
    delete editableData[key]
    getTable()
  }
  //取消
  const cancel = (key: string) => {
    delete editableData[key]
  }
  // 发送
  async function onSend() {
    const res = await send({
      token,
      data: {
        ids: [selectedRowKeys.value[0]],
      },
    })
    if (res.success === 1) {
      message.success('成功')
      if(userId){
        router.replace({name:'home'})
      }
    } else {
      message.error(res.message)
    }
  }
</script>
<style scoped>
  .control {
    a {
      color: #333;
    }
  }
  .editable-row-operations a {
    margin-right: 8px;
  }

  #price {
    .btn-group {
      display: flex;
      justify-content: end;
      margin-top: 20px;
    }
  }
</style>
